﻿using System;
using System.Windows;
using Atha.Clients.ViewModels;
using Microsoft.Win32;
using Microsoft.Windows.Controls.Ribbon;

namespace Atha.Clients.Wpf
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : RibbonWindow
	{
		private MainViewModel _viewModel;

		/// <summary>
		/// Initializes a new instance of the <see cref="MainWindow"/> class.
		/// </summary>
		public MainWindow()
		{
			this._viewModel = new MainViewModel(() => new TestScriptDirectoryReader(Environment.CurrentDirectory, true), filePath => new TestScriptFileReader(filePath), () => new TestScriptFileWriter(), new ClientTestRunner(), this.NotifyUser, this.GetExistingTestPath, this.GetNewTestSaveAsPath);

			InitializeComponent();

			this.DataContext = this._viewModel;
		}

		/// <summary>
		/// Notifies the user.
		/// </summary>
		/// <param name="notifyViewModel">The notify view model.</param>
		private void NotifyUser(NotifyViewModel notifyViewModel)
		{
			MessageBox.Show(notifyViewModel.Message);
		}

		/// <summary>
		/// Gets the new test save as path.
		/// </summary>
		/// <returns></returns>
		private string GetNewTestSaveAsPath()
		{
			string newTestPath = null;

			var dlg = new SaveFileDialog();

			if (dlg.ShowDialog(this).GetValueOrDefault())
			{
				newTestPath = dlg.FileName;
			}

			return newTestPath;
		}

		/// <summary>
		/// Gets the existing test path.
		/// </summary>
		/// <returns></returns>
		private string GetExistingTestPath()
		{
			string existingTestPath = null;

			var dlg = new OpenFileDialog();

			dlg.CheckFileExists = true;
			dlg.CheckPathExists = true;
			dlg.DefaultExt = ".py";
			dlg.Filter = "IronPython (*.py)|*.py|IronRuby (*.rb)|*.rb|PowerShell (*.ps1)|*.ps1|Razor (*.cshtml, *.vbhtml)|*.cshtml;*.vbhtml|All tests (*.*)|*.py;*.rb;*.ps1;*.cshtml;*.vbhtml";
			dlg.FilterIndex = 5; // 1-based index

			if (dlg.ShowDialog(this).GetValueOrDefault())
			{
				existingTestPath = dlg.FileName;
			}

			return existingTestPath;
		}

		private void RibbonAppMenuExit_Click(object sender, RoutedEventArgs e)
		{
			Application.Current.Shutdown();
		}
	}
}
